package com.wangjiang.foundation.common.util;

import com.wangjiang.foundation.common.constants.MdcConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * log 工具类 (线程追踪)
 * @author  wangjiang
 */
public class LogUtil {

    private static final Logger logger = LoggerFactory.getLogger(LogUtil.class);
    /**
     * 生成日志唯一追踪id
     * @return
     */
    public static String genTraceID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 当前线程是否含有traceId
     *
     */
    public static Boolean hasTraceID() {
        return CommonUtils.isNotNull(getTraceId());
    }

    /**
     * 开始线程日志追踪
     */
    public static void startTraceRandom(String uuid) {
        if (CommonUtils.isNull(getTraceId())) {
            if(CommonUtils.isNull(uuid)) {
                uuid =  genTraceID();
            }
            MDC.put(MdcConstant.TRACE_ID , uuid);
            logger.info("========= 开始追踪日志traceId: {} =========", getTraceId() );
        }
    }

    public static String getTraceId() {
        return MDC.get(MdcConstant.TRACE_ID);
    }

    /**
     * 删除日志跟踪
     */
    public static void removeTrace() {
        if (hasTraceID()) {
            logger.info("========= 结束追踪日志traceId: {} =========", getTraceId() );
            MDC.remove(MdcConstant.TRACE_ID);
        }
    }
}
